package com.wrial.kind.sort;
/*
 * @Author  Wrial
 * @Date Created in 12:51 2020/8/8
 * @Description
 */

import java.util.Arrays;

public class MergeSort {
    /**
     * 归并：先分再和
     */
    public int[] sortArray(int[] nums) {
        int[] temp = new int[nums.length];
        mergeSort(nums, 0, nums.length - 1, temp);
        return nums;
    }

    private void mergeSort(int[] nums, int start, int end, int[] temp) {
        if (start == end) return; //只剩下一个元素那就不用递归了
        int mid = (start + end) / 2;
        mergeSort(nums, start, mid, temp);
        mergeSort(nums, mid + 1, end, temp);
        merge(nums, start, mid, end, temp);
    }

    private void merge(int[] nums, int start, int mid, int end, int[] temp) {
        int tempIndex = 0;
        int p1 = start;
        int p2 = mid + 1;

        while (p1 <= mid && p2 <= end) {
            if (nums[p1] > nums[p2]) {
                temp[tempIndex++] = nums[p2++];
            } else {
                temp[tempIndex++] = nums[p1++];
            }
        }
        while (p1 <= mid) {
            temp[tempIndex++] = nums[p1++];
        }
        while (p2 <= end) {
            temp[tempIndex++] = nums[p2++];
        }

        for (int i = start; i <= end; i++) {
            nums[i] =  temp[i - start];
        }
    }

    public static void main(String[] args) {
        MergeSort mergeSort = new MergeSort();
        int[] arr1 = {-2,3,-5};
        System.out.println(Arrays.toString(arr1));
        mergeSort.sortArray(arr1);
        System.out.println(Arrays.toString(arr1));
    }

}

